<template>
  <view class="address-edit-container">
    <!-- 头部导航 -->
    <view class="header">
      <text class="save-btn" @click="saveAddress">保存</text>
    </view>
    <!-- 表单区域 -->
    <view class="form-container">
      <view class="form-item">
        <text class="label">收货人</text>
        <input class="input" v-model="form.name" placeholder="请输入收货人姓名" />
      </view>
      <view class="form-item">
        <text class="label">手机号码</text>
        <input class="input" v-model="form.phone" type="number" placeholder="请输入手机号码" />
      </view>
      <!-- 省市区选择 - 一行显示 -->
      <view class="form-item">
        <text class="label">所在地区</text>
        <view class="region-row">
          <picker mode="selector" :range="provinceList" range-key="name" @change="onProvinceChange">
            <view class="region-item" :class="{placeholder: !form.province}">
              {{ form.province || '省' }}
              <text class="arrow">▼</text>
            </view>
          </picker>
          <picker mode="selector" :range="cityList" range-key="name" @change="onCityChange" :disabled="!form.province">
            <view class="region-item" :class="{placeholder: !form.city, disabled: !form.province}">
              {{ form.city || '市' }}
              <text class="arrow">▼</text>
            </view>
          </picker>
          <picker mode="selector" :range="districtList" range-key="name" @change="onDistrictChange" :disabled="!form.city">
            <view class="region-item" :class="{placeholder: !form.district, disabled: !form.city}">
              {{ form.district || '区/县' }}
              <text class="arrow">▼</text>
            </view>
          </picker>
        </view>
      </view>
      <view class="form-item">
        <text class="label">详细地址</text>
        <textarea class="textarea" v-model="form.detailAddress" placeholder="请输入街道、楼栋号、门牌号等" auto-height />
      </view>
    </view>
    <!-- 删除按钮（编辑模式下显示） -->
    <!-- <button class="delete-btn" @click="deleteAddress" v-if="isEdit">删除地址</button> -->
  </view>
</template>

<script>
import provinces from '/src/region-data.js'; // 地区数据文件

export default {
  data() {
    return {
      isEdit: false,
      form: {
        name: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        detailAddress: '',
        isDefault: false
      },
      provinceList: [],
      cityList: [],
      districtList: []
    };
  },
  onLoad(options) {
    this.provinceList = provinces;
    if (options.edit === 'true') {
      this.isEdit = true;
      // 初始化表单数据为传递过来的原地址信息
      this.form.name = options.name;
      this.form.phone = options.phone;
      this.form.province = options.province;
      this.form.city = options.city;
      this.form.district = options.district;
      this.form.detailAddress = options.detailAddress;
      this.form.isDefault = options.isDefault === 'true';

      // 根据省份和城市加载对应的城市列表和区县列表
      if (this.form.province) {
        const selectedProvince = this.provinceList.find(p => p.name === this.form.province);
        if (selectedProvince) {
          this.cityList = selectedProvince.children || [];
          if (this.form.city) {
            const selectedCity = this.cityList.find(c => c.name === this.form.city);
            if (selectedCity) {
              this.districtList = selectedCity.children || [];
            }
          }
        }
      }
    }
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    onProvinceChange(e) {
      const index = e.detail.value;
      this.form.province = this.provinceList[index].name;
      this.form.city = '';
      this.form.district = '';
      this.cityList = this.provinceList[index].children || [];
      this.districtList = [];
    },
    onCityChange(e) {
      const index = e.detail.value;
      this.form.city = this.cityList[index].name;
      this.form.district = '';
      this.districtList = this.cityList[index].children || [];
    },
    onDistrictChange(e) {
      const index = e.detail.value;
      this.form.district = this.districtList[index].name;
    },
    saveAddress() {
      // 表单验证
      if (!this.form.name || !this.form.phone || !this.form.province || 
          !this.form.city || !this.form.district || !this.form.detailAddress) {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none'
        });
        return;
      }
      
      if (!/^1[3-9]\d{9}$/.test(this.form.phone)) {
        uni.showToast({
          title: '请输入正确的手机号码',
          icon: 'none'
        });
        return;
      }
      
      // 获取地址列表
      let addressList = uni.getStorageSync('addressList') || [];
      
      if (this.isEdit) {
        // 编辑模式 - 更新现有地址
        const index = addressList.findIndex(item => item.id === this.editId);
        if (index !== -1) {
          addressList[index] = {
            ...addressList[index],
            ...this.form
          };
        }
      } else {
        // 新增模式 - 创建新地址
        const newAddress = {
          id: Date.now().toString(), // 使用时间戳作为ID
          ...this.form
        };
        addressList.push(newAddress);
      }
      
      // 保存到本地存储
      uni.setStorageSync('addressList', addressList);
      
      uni.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 1500,
        success: () => {
          // 延迟跳转，确保用户看到保存成功的提示
          setTimeout(() => {
            uni.navigateBack(); // 返回上一页
          }, 1500);
        }
      });
    },
    deleteAddress() {
      uni.showModal({
        title: '提示',
        content: '确定要删除这个地址吗？',
        success: (res) => {
          if (res.confirm) {
            let addressList = uni.getStorageSync('addressList') || [];
            const index = addressList.findIndex(a => a.id === options.id);
            addressList.splice(index, 1);
            uni.setStorageSync('addressList', addressList);
            uni.showToast({
              title: '删除成功',
              icon: 'success',
              success: () => {
                // 同样使用 uni.redirectTo 跳转到管理地址页面，路径根据实际情况修改
                uni.navigateTo({
                  url: '/pages/addressEdit/addressEdit'
                });
              }
            });
          }
        }
      });
    }
  }
};
</script>

<style scoped>
.address-edit-container {
  padding: 15px;
  background-color: #f9f9f9;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 44px;
  background-color: white;
  margin-bottom: 15px;
  position: relative;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.05);
}

.save-btn {
  position: absolute;
  right: 15px;
  font-size: 16px;
  color: #007AFF;
  font-weight: 500;
}

.form-container {
  background-color: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.05);
}

.form-item {
  margin-bottom: 20px;
}

.label {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  display: block;
  font-weight: 500;
}

.input {
  width: 100%;
  padding: 10px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.2s ease;
}

.input:focus {
  border-color: #007AFF;
  box-shadow: 0 0 5px rgba(0, 122, 255, 0.2);
}

.region-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.region-item {
  flex: 1;
  margin-right: 10px;
  padding: 10px 12px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  font-size: 14px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: border-color 0.2s ease;
}

.region-item:last-child {
  margin-right: 0;
}

.region-item.placeholder {
  color: #999;
}

.region-item.disabled {
  background-color: #f5f5f5;
  color: #ccc;
  border-color: #ccc;
}

.arrow {
  font-size: 12px;
  color: #666;
  margin-left: 5px;
}

.textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  font-size: 14px;
  outline: none;
  resize: none;
  transition: border-color 0.2s ease;
}

.textarea:focus {
  border-color: #007AFF;
  box-shadow: 0 0 5px rgba(0, 122, 255, 0.2);
}

.delete-btn {
  background-color: #f55e5e;
  color: white;
  padding: 12px;
  border: none;
  border-radius: 25px;
  width: 90%;
  margin: 30px auto 0;
  font-size: 16px;
  box-shadow: 0 2px 5px rgba(255, 77, 79, 0.2);
  display: flex;
  justify-content: center;
  align-items: center;
  transition: background-color 0.2s ease;
}

.delete-btn:hover {
  background-color: #ff6668;
}
</style>